package com.eastfair.certificate.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.eastfair.boot.service.SuperCacheServiceImpl;
import com.eastfair.cache.projectcore.FormFieldSubSystemCacheKeyBuilder;
import com.eastfair.certificate.dao.FormFieldSubsystemMapper;
import com.eastfair.certificate.entity.FormField;
import com.eastfair.certificate.entity.FormFieldSubsystem;
import com.eastfair.certificate.service.FormFieldSubsystemService;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.code.ExceptionCode;
import com.eastfair.core.model.CacheKeyBuilder;
import com.eastfair.database.mybatis.conditions.Wraps;
import com.eastfair.database.mybatis.conditions.query.QueryWrap;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;

import java.util.*;

//import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.aop.framework.AopContext;
import com.eastfair.annotation.annotation.cache.Magic;
import com.eastfair.annotation.annotation.cache.Cache;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
//import com.baomidou.dynamic.datasource.annotation.DS;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import com.eastfair.certificate.vo.*;
import com.eastfair.certificate.dto.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * <p>
 * 业务实现类
 * 动态表单
 * </p>
 *
 * @author ligang
 * @date 2023-05-17
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class FormFieldSubsystemServiceImpl extends SuperCacheServiceImpl<FormFieldSubsystemMapper, FormFieldSubsystem> implements FormFieldSubsystemService {


    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<FormFieldSubsystem> modelList) {
        modelList.stream().forEach(s -> {
            s.setIsDeleted(BusinessConstant.YES);
        });
        // TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
        return R.successDef();
    }


    /**
     * 处理新增相关处理
     *
     * @param model 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerSave(FormFieldSubsystem model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        model.setIsDeleted(BusinessConstant.NO);
//        model.setIsEnabled(BusinessConstant.YES);
        return R.successDef();
    }


    /**
     * 通用查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    public List<FormFieldSubsystem> list(FormFieldSubsystemDTO modelDTO, List<Long> ids) {
        return ((FormFieldSubsystemService) AopContext.currentProxy()).listOfCache(modelDTO, ids);
    }


    /**
     * 缓存查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    @Cache(key = "",
            magic = @Magic(
                    key = "{" +
                            "{'languageType', #args[0]?.languageType}," +
                            "{'fieldName', #args[0]?.fieldName}," +
                            "{'fieldEnName', #args[0]?.fieldEnName}," +
                            "{'keyword', #args[0]?.keyword}," +
                            "{'fieldType', #args[0]?.fieldType}," +
                            "{'groupId', #args[0]?.groupId}," +
                            "{'fieldTypeAttribute', #args[0]?.fieldTypeAttribute}," +
                            "{'fieldTypeUrlValue', #args[0]?.fieldTypeUrlValue}," +
                            "{'methodType', #args[0]?.methodType}," +
                            "{'fieldTypeAttributeValue', #args[0]?.fieldTypeAttributeValue}," +
                            "{'placeholder', #args[0]?.placeholder}," +
                            "{'enPlaceholder', #args[0]?.enPlaceholder}," +
                            "{'fieldDesc', #args[0]?.fieldDesc}," +
                            "{'fieldEnDesc', #args[0]?.fieldEnDesc}," +
                            "{'inputLength', #args[0]?.inputLength}," +
                            "{'inputWidth', #args[0]?.inputWidth}," +
                            "{'sequence', #args[0]?.sequence}," +
                            "{'legend', #args[0]?.legend}," +
                            "{'legendDesc', #args[0]?.legendDesc}," +
                            "{'legendEnDesc', #args[0]?.legendEnDesc}," +
                            "{'isEdit', #args[0]?.isEdit}," +
                            "{'isRequired', #args[0]?.isRequired}," +
                            "{'isMultiple', #args[0]?.isMultiple}," +
                            "{'isVerification', #args[0]?.isVerification}," +
                            "{'verificationKeyword', #args[0]?.verificationKeyword}," +
                            "{'isEnabled', #args[0]?.isEnabled}," +
                            "{'relatedId', #args[0]?.relatedId}," +
                            "{'labelKey', #args[0]?.labelKey}," +
                            "{'labelValueKey', #args[0]?.labelValueKey}," +
                            "{'id', #args[1]}" +
                            "}"))
    public List<FormFieldSubsystem> listOfCache(FormFieldSubsystemDTO modelDTO, List<Long> ids) {
        //查询
        FormFieldSubsystem queryModel = new FormFieldSubsystem();
        if (modelDTO != null) {
            BeanUtils.copyProperties(modelDTO, queryModel);
        }
        QueryWrap<FormFieldSubsystem> wrapper = Wraps.q(queryModel);
        if (ids != null && !ids.isEmpty()) {
            wrapper.lambda().in(FormFieldSubsystem::getId, ids);
        }
        //添加其他业务查询条件
        wrapper.lambda().eq(FormFieldSubsystem::getIsDeleted, BusinessConstant.DELETE_NO);
        List<FormFieldSubsystem> modelList = list(wrapper);
        return modelList;
    }


    @Override
    public R<String> checkFormFieldInfo(List<FormFieldSubsystemVO> formFieldSubsystemVOS) {
        StringBuilder stringBuilder = new StringBuilder();
        // 实体/类名为空 校验失败
        if (Objects.isNull(formFieldSubsystemVOS) || CollectionUtil.isEmpty(formFieldSubsystemVOS)) {
            return R.fail(ExceptionCode.ERROR_NULL_PARAMS);
        }
        // 表单校验
        for (FormFieldSubsystemVO formFieldSubsystemVO : formFieldSubsystemVOS) {
            Object value = formFieldSubsystemVO.getValue();
            if (BusinessConstant.YES == formFieldSubsystemVO.getIsRequired()) {
                if (value == null) {
                    stringBuilder.append(String.format("%s不能为空", formFieldSubsystemVO.getFieldName()));
                }
            }
            if (!Objects.isNull(formFieldSubsystemVO.getInputLength())) {
                if (value != null && formFieldSubsystemVO.getInputLength() < value.toString().length()) {
                    stringBuilder.append(String.format("%s 长度高于 %s", formFieldSubsystemVO.getFieldName(), formFieldSubsystemVO.getInputLength()));
                }
            }
        }
        return R.success(stringBuilder.toString());
    }

    @Override
    public R<Boolean> updateFormField(FormFieldSubsystemDTO formFieldSubsystemDTO) {
        if (Objects.isNull(formFieldSubsystemDTO.getId())) {
            return R.fail(ExceptionCode.ERROR_NULL_ID);
        }
        FormFieldSubsystem formFieldSubsystem = getByIdCache(formFieldSubsystemDTO.getId());
        if (Objects.isNull(formFieldSubsystem)) {
            return R.fail(ExceptionCode.ERROR_NULL_ID);
        }
        FormFieldSubsystem fieldSubsystem = BeanUtil.copyProperties(formFieldSubsystemDTO, FormFieldSubsystem.class);
        updateById(fieldSubsystem);
        //重新排序
        updateSequece(formFieldSubsystem, fieldSubsystem.getSequence());
        return R.success();
    }

    @Override
    public R updateSequece(FormFieldSubsystem formFieldSubsystem, int sequence) {
        QueryWrapper<FormFieldSubsystem> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(FormFieldSubsystem::getIsDeleted, BusinessConstant.DELETE_NO)
                .eq(formFieldSubsystem.getGroupId() != null, FormFieldSubsystem::getGroupId, formFieldSubsystem.getGroupId())
                .ne(formFieldSubsystem.getId() != null, FormFieldSubsystem::getId, formFieldSubsystem.getId())
                .ge(FormFieldSubsystem::getSequence, sequence)
                .eq(formFieldSubsystem.getRelatedId() != null, FormFieldSubsystem::getRelatedId, formFieldSubsystem.getRelatedId())
//                .eq(formFieldSubsystem.getIsEnabled() != null, FormFieldSubsystem::getIsEnabled, formFieldSubsystem.getIsEnabled())
        ;
        queryWrapper.orderByAsc("sequence");
        List<FormFieldSubsystem> formFieldSubsystemList = list(queryWrapper);
        if (formFieldSubsystemList != null && !formFieldSubsystemList.isEmpty()) {
            for (FormFieldSubsystem fieldSubsystem : formFieldSubsystemList) {
                fieldSubsystem.setSequence(++sequence);
//                updateById(fieldSubsystem);
            }
            //批量更新
            updateBatchById(formFieldSubsystemList);
        }
        return R.success();
    }

    /**
     * do转vo
     *
     * @param model model
     * @return modelVo
     */
    @Override
    public FormFieldSubsystemVO doToVo(FormFieldSubsystem model) {
        FormFieldSubsystemVO modelVo = new FormFieldSubsystemVO();
        BeanUtils.copyProperties(model, modelVo);
        modelVo.setId(model.getId());
        return modelVo;
    }

    /**
     * do转vo
     *
     * @param modelList modelList
     * @return list
     */
    @Override
    public List<FormFieldSubsystemVO> doToVos(List<FormFieldSubsystem> modelList) {
        if (modelList == null || modelList.isEmpty()) {
            return null;
        }
        List<FormFieldSubsystemVO> result = new ArrayList<>();
        for (FormFieldSubsystem model : modelList) {
            result.add(doToVo(model));
        }
        return result;
    }

    @Override
    public CacheKeyBuilder getCacheKeyBuilder() {
        return new FormFieldSubSystemCacheKeyBuilder();
    }

    public R<List<FormFieldSubsystemVO>> listDynamicFrom(FormFieldSubsystemDTO formFieldSubsystemDTO) {
        List<FormFieldSubsystemVO> formFieldSubsystemList = doToVos(list(formFieldSubsystemDTO, null));
        if (formFieldSubsystemList == null || formFieldSubsystemList.isEmpty()) {
            return R.success(null);
        }
        //排序
        Collections.sort(formFieldSubsystemList, new Comparator<FormFieldSubsystemVO>() {
            @Override
            public int compare(FormFieldSubsystemVO u1, FormFieldSubsystemVO u2) {
                int diff = u1.getSequence() - u2.getSequence();
                if (diff > 0) {
                    return 1;
                } else if (diff < 0) {
                    return -1;
                }
                return 0; //相等为0
            }
        });

        return R.success(formFieldSubsystemList);
    }
}
